package com.threeox.commonlibrary.ui.view.engineview.tablemodel;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.R;
import com.threeox.commonlibrary.entity.engine.Lifecycle;
import com.threeox.commonlibrary.entity.engine.model.table.TableModelMessage;
import com.threeox.commonlibrary.entity.engine.model.table.TableResultMessage;
import com.threeox.commonlibrary.entity.engine.request.base.BaseRequestMsg;
import com.threeox.commonlibrary.entity.engine.request.sqlite.OperationTypeMsg;
import com.threeox.commonlibrary.entity.engine.request.sqlite.SqliteRequestMsg;
import com.threeox.commonlibrary.inter.OnRequestListener;
import com.threeox.commonlibrary.ui.view.engineview.base.CommonModelView;
import com.threeox.commonlibrary.ui.view.inter.engine.base.IBaseExtend;
import com.threeox.commonlibrary.ui.view.inter.engine.tablemodel.ITableModelExtend;
import com.threeox.commonlibrary.ui.view.inter.table.ITablePagingView;
import com.threeox.commonlibrary.ui.view.inter.table.ITableView;
import com.threeox.commonlibrary.ui.view.inter.table.OnTablePagingListener;
import com.threeox.commonlibrary.ui.view.inter.table.OnTableViewListener;
import com.threeox.commonlibrary.util.JSONUtils;
import com.threeox.commonlibrary.util.request.TableRequestHelper;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.res.LayoutUtils;
import com.threeox.utillibrary.util.sys.KeyBoardUtils;

/**
 *
 * @ClassName: TableModelView
 *
 * @Description: TODO(表格模型View)
 *
 * @author 赵屈犇
 *
 * @date 创建时间: 2017/8/14 17:43
 *
 * @version 1.0
 *
 */
public class TableModelView extends CommonModelView implements OnTablePagingListener, OnTableViewListener, OnRequestListener {

    protected TableModelMessage mTableModelMessage;// 表格模型对象的实体类

    protected ITableView mTableView;
    protected LinearLayout mTableModelLayout;
    protected ITablePagingView mTablePagingView;

    protected BaseRequestMsg mBaseRequestMsg;// 请求对象
    protected TableRequestHelper mTableRequestHelper;// 表格请求帮助类

    protected ITableModelExtend mTableModelExtend;

    public TableModelView(Context context) {
        this(context, null);
    }

    public TableModelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TableModelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initView() {
        super.initView();
        LayoutUtils.inflate(mContext, R.layout.view_tablemodel, this);
        this.mTableModelLayout = findViewById(R.id.id_table_model_layout);
        this.mContainerLayout = findViewById(R.id.id_table_model_container);
    }

    @Override
    public void initData(Intent intent) {
        super.initData(intent);
        if (mTableModelMessage != null) {
            setBaseModelMsg(mTableModelMessage);
            fillInView();
            initRequestMsg();
            executeRequest();
        }
    }

    @Override
    public TableModelMessage initModelMessage(int fileName) {
        if (mTableModelMessage == null) {
            if (mFileName == -1){
                LogUtils.e(TAG, NOTMODELFILE);
                return null;
            }
            mTableModelMessage = mCommonConfig.getTableModelMessage(mFileName);
        }
        return mTableModelMessage;
    }

    /**
     * 初始化View
     */
    private void fillInView() {
        initPublic();
        initCommonView();
        initTableView();
        initTablePagingView();
        initExtend();
    }

    /**
     * 初始化表格View
     */
    private void initTableView() {
        this.mTableView = mOverallInitView.initTableModelTableView();
        this.mTableView.initConfig(mTableModelMessage);
        if (mTableView instanceof View) {
            LayoutParams layoutParams = mLayoutParamsUtils.getLinearLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.weight = 1;
            ((View) mTableView).setLayoutParams(layoutParams);
            this.mTableModelLayout.addView((View) mTableView);
        }
        mTableView.setOnTableViewListener(this);
    }

    /**
     * 初始化表格的分页View
     */
    private void initTablePagingView() {
        this.mTablePagingView = mOverallInitView.initTablePagingView();
        this.mTablePagingView.setOnTablePagingListener(this);
        if (mTablePagingView instanceof View) {
            LayoutParams layoutParams = mLayoutParamsUtils.getLinearLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ((View) mTablePagingView).setLayoutParams(layoutParams);
            this.mTableModelLayout.addView((View) mTablePagingView);
            if (!mTableModelMessage.isLimit()) {
                ((View) mTablePagingView).setVisibility(GONE);
            } else {
                ((View) mTablePagingView).setVisibility(VISIBLE);
            }
        }
    }

    @Override
    protected void initExtend() {
        if (mBaseExtend != null && mBaseExtend instanceof ITableModelExtend) {
            mTableModelExtend = (ITableModelExtend) mBaseExtend;
            mTableModelExtend.init(mContext, this);
        }
    }

    /**
     * 初始化请求对象
     */
    @Override
    protected void initRequestMsg() {
        super.initRequestMsg();
        mBaseRequestMsg = mTableModelMessage.getBaseRequestMsg();
        if (mBaseRequestMsg != null && mBaseRequestMsg instanceof SqliteRequestMsg) {
            ((SqliteRequestMsg) mBaseRequestMsg).setOperationType(OperationTypeMsg.SELECTTABLE);
        }
        this.mTableRequestHelper = TableRequestHelper.newInstance();
        mTableRequestHelper.setIntent(mIntent);
        mTableRequestHelper.setOnRequestListener(this);
    }

    @Override
    protected boolean verify(JSONObject value) {
        return true;
    }

    /**
     * 执行请求操作
     */
    private void executeRequest() {
        if (mTableModelMessage.isExecute()) {
            homePage();
        }
    }

    public TableModelMessage getTableModelMessage() {
        return mTableModelMessage;
    }

    public ITableModelExtend getTableModelExtend() {
        return mTableModelExtend;
    }

    /**
     * 获取请求信息
     *
     * @return
     */
    public BaseRequestMsg getBaseRequestMsg() {
        return mBaseRequestMsg;
    }

    public ITableView getTableView() {
        return mTableView;
    }

    /**
     * 添加请求数据
     *
     * @param key
     * @param val
     */
    public void putRequestParam(String key, Object val) {
        if (mBaseRequestMsg != null) {
            mBaseRequestMsg.putRequestParam(key, val);
        }
    }

    /**
     * 根据Key只得到指定的参数
     *
     * @param key
     * @return
     */
    public <T extends Object> T getRequestParam(String key) {
        if (mBaseRequestMsg != null) {
            return (T) mBaseRequestMsg.getRequestParam(key);
        }
        return null;
    }

    /**
     * 根据Key 删除
     * @param key
     */
    public void removeRequestParam(String key) {
        if (mBaseRequestMsg != null) {
            mBaseRequestMsg.removeRequestParam(key);
        }
    }

    /**
     * 执行请求
     */
    public void execute() {
        requestIn();
        mTableRequestHelper.execRequest(mBaseRequestMsg);
    }

    @Override
    public void onSuccess(BaseRequestMsg requestMsg, String url, int id, String msg, Object data) {
        if (requestMsg != null) {
            putRequestResult(requestMsg.getKey(), data);
        }
        if (mTableModelExtend != null) {
            TableResultMessage result = mTableModelExtend.onParseData(data);
            if (result != null) {
                data = result;
            }
        }
        if (data instanceof TableResultMessage) {
            TableResultMessage tableResultMessage = (TableResultMessage) data;
            if (mTableModelExtend != null && !mTableModelExtend.onBeforeParseData(tableResultMessage)) {
                return;
            }
            mTableView.setVisibility(VISIBLE);
            mTableView.setValue(tableResultMessage.getColumnNames(), tableResultMessage.getDatas());
            mTablePagingView.setMaxPageNumber(tableResultMessage.getPageSize());
            if (mTableModelExtend != null) {
                mTableModelExtend.onAfterParseData(tableResultMessage);
            }
        } else {
            onError(requestMsg, url, id, -1, "表格结果不正确:必须为TableResultMessage对象!", null);
        }
    }

    @Override
    public void onError(BaseRequestMsg requestMsg, String url, int id, Object code, String msg, Object data) {
        showToast(msg);
        if (mTableModelExtend != null) {
            mTableModelExtend.onRequestError(requestMsg, url, id, code, msg);
        }
        requestFault(code, msg);
    }

    @Override
    public void inProgress(BaseRequestMsg requestMsg, float progress, long total, int id, String url) {
        if (mTableModelExtend != null) {
            mTableModelExtend.onRequestInProgress(requestMsg, progress, total, id, url);
        }
    }

    @Override
    public void OnTableRowClick(int position, Object data) {
        if (mTableModelExtend != null) {
            mTableModelExtend.OnTableRowClick(position, data);
        }
    }

    @Override
    public Boolean OnTableRowLongClick(int position, Object data) {
        if (mTableModelExtend != null) {
            return mTableModelExtend.OnTableRowLongClick(position, data);
        }
        return null;
    }

    @Override
    public void onTableShowSuccess() {
        requestSucceed(null);
    }

    @Override
    public void onTableShowFeated(String message) {
        requestFault(-1, message);
    }

    /*=================表格分页的回调=================*/
    @Override
    public void homePage() {
        String pageName = mTableModelMessage.getPageName();
        if (mBaseRequestMsg != null) {// 属于本地SQLITE数据库请求
            if (mTableModelMessage.isLimit()) {
                mBaseRequestMsg.putRequestParam(SqliteRequestMsg.OFFSET, 0);
                if (EmptyUtils.isEmpty(pageName)) {
                    mTableModelMessage.setPageName(SqliteRequestMsg.OFFSET);
                }
            }
        }
        mTablePagingView.setNowPageNumber(1);
        requestIn();
        mTableRequestHelper.execRequest(mBaseRequestMsg);
    }

    @Override
    public void previousPage() {
        String pageName = mTableModelMessage.getPageName();
        if (EmptyUtils.isNotEmpty(pageName)) { // 判断是否有pageName
            int pageNum = 0;
            try {
                pageNum = Integer.parseInt(String.valueOf(JSONUtils.getJSONValue(mBaseRequestMsg.getRequestParam(), pageName)));// 取得当前第几页
                --pageNum;
            } catch (Exception e) {
                pageNum = -1;
            }
            if (pageNum > 0) {
                JSONUtils.putJSONValue(mBaseRequestMsg.getRequestParam(), pageName, pageNum);
            } else {
                showToast("已经到达首页啦!");
                return;
            }
            mTablePagingView.setNowPageNumber(pageNum + 1);
        }
        requestIn();
        mTableRequestHelper.execRequest(mBaseRequestMsg);
    }

    @Override
    public void nextPage() {
        Long pageNumber = mTablePagingView.getMaxPageNumber();
        String pageName = mTableModelMessage.getPageName();
        if (EmptyUtils.isNotEmpty(pageName) && pageNumber != null) { // 判断是否有pageName
            int pageNum = 0;
            try {
                pageNum = Integer.parseInt(String.valueOf(JSONUtils.getJSONValue(mBaseRequestMsg.getRequestParam(), pageName)));// 取得当前第几页
                ++pageNum;
            } catch (Exception e) {
                pageNum = -1;
            }
            if (pageNum >= Integer.parseInt(String.valueOf((pageNumber)))) {
                showToast("已经到达最后一页啦!");
                return;
            }
            if (pageNum != -1) {
                JSONUtils.putJSONValue(mBaseRequestMsg.getRequestParam(), pageName, pageNum);
            }
            mTablePagingView.setNowPageNumber(pageNum + 1);
        }
        requestIn();
        mTableRequestHelper.execRequest(mBaseRequestMsg);
    }

    @Override
    public void finalPage() {
        Long pageNumber = mTablePagingView.getMaxPageNumber();
        if (pageNumber != null) {
            requestIn();
            String pageName = mTableModelMessage.getPageName();
            if (EmptyUtils.isNotEmpty(pageName)) { // 判断是否有pageName
                if (mTableModelMessage.isLimit()) {
                    mBaseRequestMsg.putRequestParam(SqliteRequestMsg.OFFSET, Integer.valueOf(String.valueOf(pageNumber - 1)));
                    if (EmptyUtils.isEmpty(pageName)) {
                        mTableModelMessage.setPageName(SqliteRequestMsg.OFFSET);
                    }
                }
            }
            mTableRequestHelper.execRequest(mBaseRequestMsg);
            mTablePagingView.setNowPageNumber(Integer.parseInt(String.valueOf(pageNumber)));
        }
    }

    @Override
    public void jumpPage(int pageNumber) {
        if (pageNumber > 0) {
            requestIn();
            String pageName = mTableModelMessage.getPageName();
            if (EmptyUtils.isNotEmpty(pageName)) { // 判断是否有pageName
                if (mTableModelMessage.isLimit()) {
                    mBaseRequestMsg.putRequestParam(SqliteRequestMsg.OFFSET, Integer.valueOf(String.valueOf(pageNumber - 1)));
                    if (EmptyUtils.isEmpty(pageName)) {
                        mTableModelMessage.setPageName(SqliteRequestMsg.OFFSET);
                    }
                }
            }
            mTableRequestHelper.execRequest(mBaseRequestMsg);
            mTablePagingView.setNowPageNumber(Integer.parseInt(String.valueOf(pageNumber)));
        }
        KeyBoardUtils.hideSoftInputView(mContext);
    }

    /*=================表格分页的回调=================*/

    @Override
    public boolean onLifecycle(Lifecycle lifecycle, Object... params) {
        if (Lifecycle.onDestroy == lifecycle) {
            mTableView.release();
        }
        return super.onLifecycle(lifecycle, params);
    }
}
